import http from './interface';
import baseUrl from "@/util/path.js"
import store from '../../store';
// console.log('store',store);
let promise;
/**
 * 将业务所有接口统一起来便于维护
 * 如果项目很大可以将 url 独立成文件，接口分成不同的模块
 * 
 */

// 单独导出(测试接口) import {test} from '@/common/vmeitime-http/'
export const api = (data,li) => {
	// 
	let requestUrl = baseUrl.wy;
	if(li) {
		requestUrl = baseUrl.lb;
	}
	http.config.baseUrl = requestUrl;
	//debugger;
	//设置请求前拦截器
	http.interceptor.request = (config) => {
		const token = uni.getStorageSync('token');
		if(token) {
			config.header['Authorization'] = 'Bearer ' + token;
			return true;
		} else {
			//debugger;
			store.commit('setShowLogin',true)
			// uni.navigateTo({
			// 	url:'/pages/sigUP/sigUP'
			// })
			return false;
		}
		// console.log('请求前结束')
	}
	//设置请求结束后拦截器
	http.interceptor.response = async (response) => {
		    const res = await handle401(response,data,li);
			return response
		//判断返回状态 执行相应操作
	}
    return http.request({
		baseUrl: http.config.baseUrl,
        url: data.url,
		dataType: 'json',
        data:data.data,
		method:data.method
    })
}


async function handle401(response,data,li) {
	const res =  await refresh(); 
	console.log('刷新token返回值',res);
	if(res) {	
		 uni.setStorageSync('token',res.access_token)
		 uni.setStorageSync('refresh',res.refresh_token)
		 let config = response.config;
		 const resold = await api(data,li);
		 //console.log('resold',resold);
		 return resold
	} else {
		return false;
	}
}

function refresh(){
	// debugger;
	if(promise) {
		return promise;
	}
	promise = new Promise((resolve, reject) => {
		uni.showLoading({
			title: '更新登录'
		});
		uni.getStorage({
			key: 'refresh',
			success: function(res) {
				// console.log('refresh',res.data);
				if(res.data) {
					uni.request({
						url: baseUrl.lb + "oauth/token",
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						method:'post',
						data: {
							grant_type:'refresh_token',
							client_id:baseUrl.client_id,
							client_secret:baseUrl.client_secret,
							refresh_token:res.data,
							scope:''
						},
						success: (res) => {
							uni.hideLoading();
							if (res.data != 401) {
								resolve(res.data);
							} else { //跳登录
							    console.log('刷新token不是401跳登录');
								var pages = getCurrentPages();
								const route = pages[pages.length - 1].$page
							    //token失效
								console.log(route);
								let url = route.path;
								let id = route.options.id;
								if(id) {
									store.commit('setShowLogin',true)
							
								} else {
									store.commit('setShowLogin',true)
								}
								reject(res);	
							}
						},
						fail: (err) => {
							reject(err);
							window.location.reload();
						}
					})
				} else {
					// debugger;
					store.commit('setShowLogin',true)
					console.log(store.state.app.showLogin);
					uni.hideLoading();
					reject(res)
				}
				// requestData.access_token = res.data;
				
			},
			fail: (err) => {
				uni.hideLoading();
				//取出token失败
				console.log('取出刷新token失败');
				var pages = getCurrentPages();
				const route = pages[pages.length - 1].$page
				//token失效
				console.log(route);
				let url = route.path;
				let id = route.options.id;
				// console.log('跳登录接口',route.options.url);
				// console.log(url);
				// console.log(id);
				store.commit('setShowLogin',true);
				// if(id) {
				// 	uni.navigateTo({
				// 		url: '/pages/login/login?url='+ url +"?id=" + id
				// 	});
				// } else {
				// 	uni.navigateTo({
				// 		url: '/pages/login/login?url='+ url
				// 	});
				// }
				reject(err)
			}
		});
	
	})
	promise.finally(() => {
		promise = null;
	})
	
	return promise;
}




// 默认全部导出  import api from '@/common/vmeitime-http/'
export default api
